/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hu.bme.j2ee.v37zen.beans;

import hu.bme.j2ee.v37zen.entities.Dial;
import java.net.MalformedURLException;
import java.net.URL;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 *
 * @author Kiss Dániel
 */
@Stateless
@LocalBean
public class CreateDialBean {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    public Dial createDial(URL url, int order){
        Dial dial = new Dial();
        dial.setUrl(url);
        dial.setOrder(order);
        try {
            Document doc = Jsoup.connect(url.toString()).get();
            Elements title = doc.select("html head title");
            dial.setTitle(title.text());
            Elements favico = doc.select("html head link[rel=shortcut icon]");
            String href = favico.attr("href");
            try {
                URL hrefURL = new URL(href);
                dial.setFile(hrefURL.toString());
            } catch (MalformedURLException ex) {
                dial.setFile(url.getProtocol() + "://" + url.getHost() + "/favicon.ico");           
            } 
            
        } catch (Exception ex) {
            dial.setTitle(url.getHost());
            dial.setFile(url.getProtocol() + "://" + url.getHost() + "/favicon.ico");
        }
        
        dial.setFile(url.getProtocol() + "://" + url.getHost() + "/favicon.ico");
        return dial;
    }
}
